package cn.holy.app.xcddt.ui.activity.manager

import androidx.lifecycle.Observer
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.TextView
import cn.holy.app.xcddt.R
import cn.holy.app.xcddt.app.App
import cn.holy.app.xcddt.domain.RecordBean
import cn.holy.app.xcddt.net.callback.ProgressCallback
import cn.holy.app.xcddt.repository.RecordRepository
import cn.holy.app.xcddt.ui.activity.base.BaseActivity
import cn.holy.app.xcddt.utils.HDateUtils
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.kaopiz.kprogresshud.KProgressHUD
import com.orhanobut.logger.Logger
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import com.qmuiteam.qmui.widget.QMUIProgressBar
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.zhy.adapter.recyclerview.CommonAdapter
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter
import com.zhy.adapter.recyclerview.base.ViewHolder
import kotlinx.android.synthetic.main.activity_manager_list.*
import java.util.*
import javax.inject.Inject

/**
 * Created by 69568 on 2018/2/24.
 */

@Route(path = "/app/manager/list")
class ManagerListActivity : BaseActivity() {


    @Inject
    lateinit var recordRepository: RecordRepository

    var groups: ArrayList<RecordBean> = ArrayList()
    var checkedList: ArrayList<RecordBean> = ArrayList()
    lateinit var commonAdapter: CommonAdapter<RecordBean>
    lateinit var rightActionButton: Button
    var isEdit = false
    var record_num: Int = 0
    override fun initData() {
        checkedList.clear()
        record_num = intent.getIntExtra("record_num", 0)

        recordRepository.loadRecords(record_num)?.observe(this, Observer<MutableList<RecordBean>> { t ->
            groups.clear()
            if (t != null) {

                groups.addAll(t)
            }
            Logger.d(groups)
            commonAdapter.notifyDataSetChanged()
        })
    }

    override fun initView() {
        App.appComponent.inject(this)
        QMUIStatusBarHelper.translucent(this)
        QMUIStatusBarHelper.setStatusBarDarkMode(this)
        top_bar.setTitle("案卷管理").setTextColor(ContextCompat.getColor(this, R.color.colorWhite))
        top_bar.addLeftImageButton(R.mipmap.ic_back, R.id.action_close).setOnClickListener({ finish() })
        rightActionButton = top_bar.addRightTextButton(R.string.action_edit, R.id.action_edit)
        rightActionButton.setTextColor(ContextCompat.getColor(this, R.color.colorWhite))
        rightActionButton.setOnClickListener {
            isEdit = !isEdit
            if (isEdit) {
                toolbar.visibility = View.VISIBLE
                rightActionButton.text = "取消"
            } else {
                toolbar.visibility = View.GONE
                rightActionButton.text = "编辑"
            }
            commonAdapter.notifyDataSetChanged()
        }

        val linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        recyclerView.layoutManager = linearLayoutManager
        recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))

        commonAdapter = object : CommonAdapter<RecordBean>(this, R.layout.layout_record_item, groups) {
            override fun convert(holder: ViewHolder, recordBean: RecordBean, position: Int) {
                holder.getView<TextView>(R.id.tv_record_no).text = "案卷编号：" + recordBean.record_no
                holder.getView<TextView>(R.id.tv_message).text = recordBean.message
                holder.getView<TextView>(R.id.tv_address).text = recordBean.address
                holder.getView<TextView>(R.id.tv_time).text = "暂存时间：" + HDateUtils.dateToStrLong(recordBean.record_date)
                val textView = holder.getView<TextView>(R.id.tv_upload_status)
                textView.text = if (recordBean.upload == 1) "已上传" else "未上传"
                textView.setTextColor(if (recordBean.upload == 1) ContextCompat.getColor(this@ManagerListActivity, R.color.qmui_config_color_15_pure_black) else ContextCompat.getColor(this@ManagerListActivity, R.color.qmui_config_color_red))
                val checkBox = holder.getView<CheckBox>(R.id.cb_record_item)
                checkBox.isChecked = checkedList.contains(recordBean)
                if (isEdit) {
                    checkBox.visibility = View.VISIBLE
                } else {
                    checkBox.visibility = View.GONE
                }
            }
        }
        commonAdapter.setOnItemClickListener(object : MultiItemTypeAdapter.OnItemClickListener {
            override fun onItemClick(view: View?, holder: RecyclerView.ViewHolder?, position: Int) {
                val recordBean = groups[position]
                if (isEdit) {
                    if (recordBean.upload == 0) {
                        if (checkedList.contains(recordBean)) {
                            checkedList.remove(recordBean)
                        } else {
                            checkedList.add(recordBean)
                        }
                        commonAdapter.notifyDataSetChanged()
                    } else {
                        showTips("已上传案卷无需再次上传", QMUITipDialog.Builder.ICON_TYPE_INFO)
                    }

                } else {
                    if (recordBean.upload == 0) {
                        ARouter.getInstance().build("/app/record/detail").withInt("id", recordBean.id).navigation()
                    } else {

                    }
                }
            }

            override fun onItemLongClick(view: View?, holder: RecyclerView.ViewHolder?, position: Int): Boolean {
                return true
            }

        })


        recyclerView.adapter = commonAdapter
        btn_delete.setOnClickListener {
            recordRepository.removeRecords(checkedList)
            showTips("删除成功", QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
        }
        btn_upload.setOnClickListener {
            QMUIDialog.MessageDialogBuilder(this)
                    .setTitle("提示").setMessage("确认上传案卷吗？")
                    .addAction(QMUIDialogAction(this, "取消", QMUIDialogAction.ActionListener { dialog, index ->
                        dialog.dismiss()

                    }))
                    .addAction(QMUIDialogAction(this, "确定", QMUIDialogAction.ActionListener { dialog, index ->
                        dialog.dismiss()
//                        val loading = getLoading("正在上传..")
//                        loading.show()
                        val hud = KProgressHUD.create(this)
                                .setStyle(KProgressHUD.Style.PIE_DETERMINATE)
                                .setMaxProgress(checkedList.size)
                                .setLabel("正在上传...")
                                .show()

                        recordRepository.uploadLocalRecords(checkedList, object : ProgressCallback {
                            override fun onProgress(total: Int, progress: Int) {
                                Logger.d(progress)
                                hud.setProgress(progress)
                            }

                            override fun onCompleted() {

                            }

                            override fun onSuccess() {
                                hud.dismiss()
                                showTips("上传完成", QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
                            }


                            override fun onError(msg: String) {
                                hud.dismiss()
                                showTips(msg, QMUITipDialog.Builder.ICON_TYPE_FAIL)
                            }

                            override fun onStart() {

                            }

                        })
                    }))
                    .create()
                    .show()

        }
    }

    override fun initLayout() {
        setContentView(R.layout.activity_manager_list)
    }


}